const pool = require('../config/db');

class Address {
  // 创建地址
  static async create(addressData) {
    const { user_id, recipient, phone, province, city, district, detail, is_default = false } = addressData;
    
    const connection = await pool.getConnection();
    try {
      await connection.beginTransaction();

      // 如果设置为默认地址，先取消其他默认地址
      if (is_default) {
        await connection.execute(
          'UPDATE addresses SET is_default = FALSE WHERE user_id = ?',
          [user_id]
        );
      }

      const [result] = await connection.execute(
        `INSERT INTO addresses (user_id, recipient, phone, province, city, district, detail, is_default)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
        [user_id, recipient, phone, province, city, district, detail, is_default]
      );

      await connection.commit();
      return result.insertId;
    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  }

  // 根据用户ID查找地址
  static async findByUserId(user_id) {
    const [rows] = await pool.execute(
      'SELECT * FROM addresses WHERE user_id = ? ORDER BY is_default DESC, created_at DESC',
      [user_id]
    );
    return rows;
  }

  // 根据ID查找地址
  static async findById(id) {
    const [rows] = await pool.execute(
      'SELECT * FROM addresses WHERE id = ?',
      [id]
    );
    return rows[0] || null;
  }

  // 查找用户默认地址
  static async findDefaultByUserId(user_id) {
    const [rows] = await pool.execute(
      'SELECT * FROM addresses WHERE user_id = ? AND is_default = TRUE',
      [user_id]
    );
    return rows[0] || null;
  }

  // 更新地址
  static async update(id, addressData) {
    const { recipient, phone, province, city, district, detail, is_default, user_id } = addressData;
    
    const connection = await pool.getConnection();
    try {
      await connection.beginTransaction();

      // 如果设置为默认地址，先取消其他默认地址
      if (is_default) {
        await connection.execute(
          'UPDATE addresses SET is_default = FALSE WHERE user_id = ?',
          [user_id]
        );
      }

      const [result] = await connection.execute(
        `UPDATE addresses SET recipient = ?, phone = ?, province = ?, city = ?, district = ?, 
         detail = ?, is_default = ?, updated_at = NOW() WHERE id = ?`,
        [recipient, phone, province, city, district, detail, is_default, id]
      );

      await connection.commit();
      return result.affectedRows > 0;
    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  }

  // 删除地址
  static async delete(id, user_id) {
    const [result] = await pool.execute(
      'DELETE FROM addresses WHERE id = ? AND user_id = ?',
      [id, user_id]
    );
    return result.affectedRows > 0;
  }

  // 设置默认地址
  static async setDefault(id, user_id) {
    const connection = await pool.getConnection();
    try {
      await connection.beginTransaction();

      // 先取消所有默认地址
      await connection.execute(
        'UPDATE addresses SET is_default = FALSE WHERE user_id = ?',
        [user_id]
      );

      // 设置新的默认地址
      const [result] = await connection.execute(
        'UPDATE addresses SET is_default = TRUE, updated_at = NOW() WHERE id = ? AND user_id = ?',
        [id, user_id]
      );

      await connection.commit();
      return result.affectedRows > 0;
    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  }

  // 获取完整地址
  static getFullAddress(address) {
    if (!address) return '';
    return `${address.province || ''}${address.city || ''}${address.district || ''}${address.detail || ''}`;
  }
}

module.exports = Address;